package com.example.questionnaires.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.questionnaires.common.PageResult;
import com.example.questionnaires.common.Result;
import com.example.questionnaires.entity.ForumPost;
import com.example.questionnaires.entity.ForumComment;
import com.example.questionnaires.entity.User;
import com.example.questionnaires.mapper.ForumPostMapper;
import com.example.questionnaires.mapper.ForumCommentMapper;
import com.example.questionnaires.mapper.UserMapper;
import com.example.questionnaires.service.ForumService;
import com.example.questionnaires.utils.UserContext;
import com.example.questionnaires.vo.ForumPostVO;
import com.example.questionnaires.vo.ForumCommentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.time.LocalDateTime;

@Slf4j
@Service
public class ForumServiceImpl implements ForumService {
    @Autowired
    private ForumPostMapper postMapper;

    @Autowired
    private ForumCommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<PageResult<ForumPostVO>> listPosts(Integer page, Integer size) {
        // 1. 获取当前用户
        User currentUser = UserContext.getCurrentUser();
        
        // 2. 分页查询帖子
        Page<ForumPost> postPage = postMapper.selectPage(
            new Page<>(page, size),
            new LambdaQueryWrapper<ForumPost>()
                .eq(ForumPost::getDeleted, false)
                .orderByDesc(ForumPost::getCreateTime)
        );
        
        // 3. 获取所有作者ID
        Set<Long> userIds = postPage.getRecords().stream()
            .map(ForumPost::getUserId)
            .collect(Collectors.toSet());
            
        // 4. 批量查询用户信息
        final Map<Long, User> userMap = userIds.isEmpty() ? 
            new HashMap<>() : 
            userMapper.selectBatchIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        // 5. 转换为VO
        List<ForumPostVO> voList = postPage.getRecords().stream().map(post -> {
            ForumPostVO vo = new ForumPostVO();
            BeanUtils.copyProperties(post, vo);
            
            // 设置作者信息
            User author = userMap.get(post.getUserId());
            if (author != null) {
                vo.setUsername(author.getUsername());
                vo.setAvatar(null); // 暂时不设置头像
            }
            
            // 设置是否是作者
            vo.setIsAuthor(currentUser != null && currentUser.getId().equals(post.getUserId()));
            
            return vo;
        }).collect(Collectors.toList());
        
        return Result.success(PageResult.build(voList, postPage.getTotal(), postPage.getSize(), postPage.getCurrent()));
    }

    @Override
    @Transactional
    public Result<ForumPostVO> getPost(Long id) {
        // 1. 获取帖子信息
        ForumPost post = postMapper.selectById(id);
        if (post == null || post.getDeleted()) {
            return Result.error("帖子不存在");
        }

        // 2. 增加浏览量
        post.setViewCount(post.getViewCount() + 1);
        postMapper.updateById(post);

        // 3. 转换为VO
        ForumPostVO vo = new ForumPostVO();
        BeanUtils.copyProperties(post, vo);

        // 4. 获取作者信息
        User author = userMapper.selectById(post.getUserId());
        if (author != null) {
            vo.setUsername(author.getUsername());
            vo.setAvatar(null); // 暂时不设置头像
        }

        // 5. 设置是否是作者（未登录时为false）
        User currentUser = UserContext.getCurrentUser();
        vo.setIsAuthor(currentUser != null && currentUser.getId().equals(post.getUserId()));

        return Result.success(vo);
    }

    @Override
    public Result<Void> createPost(ForumPost post) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("请先登录");
        }

        post.setUserId(currentUser.getId());
        post.setStatus(0);
        post.setViewCount(0);
        post.setCommentCount(0);

        postMapper.insert(post);
        return Result.success();
    }

    @Override
    public Result<Void> deletePost(Long id) {
        // 1. 获取帖子信息
        ForumPost post = postMapper.selectById(id);
        if (post == null || post.getDeleted()) {
            return Result.error("帖子不存在");
        }

        // 2. 检查权限
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("请先登录");
        }

        // 只有作者和管理员可以删除
        if (!currentUser.getId().equals(post.getUserId()) && !currentUser.getIsAdmin()) {
            return Result.error("无权限删除");
        }

        // 3. 删除帖子
        postMapper.deleteById(id);

        return Result.success();
    }

    @Override
    public Result<PageResult<ForumCommentVO>> listComments(Long postId, Integer page, Integer size) {
        // 1. 获取当前用户（可能为null）
        User currentUser = UserContext.getCurrentUser();

        // 2. 分页查询评论
        Page<ForumComment> commentPage = commentMapper.selectPage(
            new Page<>(page, size),
            new LambdaQueryWrapper<ForumComment>()
                .eq(ForumComment::getPostId, postId)
                .eq(ForumComment::getDeleted, false)
                .isNull(ForumComment::getParentId)  // 只查询一级评论
                .orderByDesc(ForumComment::getCreateTime)
        );

        // 3. 获取所有评论的用户ID
        final Set<Long> userIds = new HashSet<>();
        
        // 收集所有评论（包括子评论）的用户ID
        final List<ForumComment> allChildComments = commentMapper.selectList(
            new LambdaQueryWrapper<ForumComment>()
                .eq(ForumComment::getPostId, postId)
                .eq(ForumComment::getDeleted, false)
                .isNotNull(ForumComment::getParentId)
        );
        
        commentPage.getRecords().forEach(comment -> userIds.add(comment.getUserId()));
        allChildComments.forEach(comment -> userIds.add(comment.getUserId()));

        // 4. 批量查询用户信息
        final Map<Long, User> userMap;
        if (userIds.isEmpty()) {
            userMap = new HashMap<>();
        } else {
            userMap = userMapper.selectBatchIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        }

        // 5. 构建父子评论关系
        final Map<Long, List<ForumComment>> parentChildMap = allChildComments.stream()
            .collect(Collectors.groupingBy(ForumComment::getParentId));

        // 6. 转换为VO
        List<ForumCommentVO> voList = commentPage.getRecords().stream()
            .map(comment -> convertToCommentVO(comment, userMap, parentChildMap, currentUser))
            .collect(Collectors.toList());

        return Result.success(PageResult.build(voList, commentPage.getTotal(), commentPage.getSize(), commentPage.getCurrent()));
    }

    @Override
    public Result<Void> addComment(ForumComment comment) {
        // 1. 检查登录状态
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("请先登录");
        }

        // 2. 检查帖子是否存在
        ForumPost post = postMapper.selectById(comment.getPostId());
        if (post == null || post.getDeleted()) {
            return Result.error("帖子不存在");
        }

        // 3. 如果是回复评论，检查父评论是否存在
        if (comment.getParentId() != null) {
            ForumComment parentComment = commentMapper.selectById(comment.getParentId());
            if (parentComment == null || parentComment.getDeleted()) {
                return Result.error("回复的评论不存在");
            }
        }

        // 4. 保存评论
        comment.setUserId(currentUser.getId());
        comment.setStatus(0);
        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        commentMapper.insert(comment);

        // 5. 更新帖子评论数
        post.setCommentCount(post.getCommentCount() + 1);
        postMapper.updateById(post);

        return Result.success();
    }

    @Override
    public Result<Void> deleteComment(Long id) {
        // 1. 获取评论信息
        ForumComment comment = commentMapper.selectById(id);
        if (comment == null || comment.getDeleted()) {
            return Result.error("评论不存在");
        }

        // 2. 检查权限
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("请先登录");
        }

        // 只有评论作者和管理员可以删除
        if (!currentUser.getId().equals(comment.getUserId()) && !currentUser.getIsAdmin()) {
            return Result.error("无权限删除");
        }

        // 3. 删除评论
        commentMapper.deleteById(id);

        // 4. 更新帖子评论数
        ForumPost post = postMapper.selectById(comment.getPostId());
        if (post != null) {
            post.setCommentCount(post.getCommentCount() - 1);
            postMapper.updateById(post);
        }

        return Result.success();
    }

    // 辅助方法：转换评论为VO
    private ForumCommentVO convertToCommentVO(ForumComment comment, Map<Long, User> userMap,
                                            Map<Long, List<ForumComment>> parentChildMap, User currentUser) {
        ForumCommentVO vo = new ForumCommentVO();
        vo.setId(comment.getId());
        vo.setContent(comment.getContent());
        
        // 设置作者信息
        User author = userMap.get(comment.getUserId());
        vo.setAuthorId(comment.getUserId());
        vo.setAuthorName(author != null ? author.getUsername() : "未知用户");
        vo.setAuthorAvatar(null); // 暂时不设置头像
        
        vo.setCreateTime(comment.getCreateTime());
        vo.setUpdateTime(comment.getUpdateTime());
        
        // 设置父评论信息
        if (comment.getParentId() != null) {
            ForumComment parent = commentMapper.selectById(comment.getParentId());
            if (parent != null) {
                User parentAuthor = userMap.get(parent.getUserId());
                vo.setParentId(parent.getId());
                vo.setParentAuthorId(parent.getUserId());
                vo.setParentAuthorName(parentAuthor != null ? parentAuthor.getUsername() : "未知用户");
                vo.setParentAuthorAvatar(null); // 暂时不设置头像
            }
        }
        
        // 设置是否是作者
        vo.setIsAuthor(currentUser != null && currentUser.getId().equals(comment.getUserId()));
        
        // 设置子评论
        List<ForumComment> children = parentChildMap.get(comment.getId());
        if (children != null && !children.isEmpty()) {
            vo.setChildren(children.stream()
                .map(child -> convertToCommentVO(child, userMap, parentChildMap, currentUser))
                .collect(Collectors.toList()));
        }
        
        return vo;
    }
}
